<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="70px">
                <el-form-item label="提出领导">
                    <el-input v-model="search.proposeLeader" placeholder="请输入提出领导" clearable/>
                </el-form-item>
                <el-form-item label="责任科室">
                    <el-select v-model="search.deptName" placeholder="请选择" clearable>
                        <el-option v-for="item, i in ksList" :key="i" :label="item.label" :value="item.label" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工作状态">
                    <el-select v-model="search.finishState" placeholder="请选择工作状态" clearable>
                        <el-option v-for="item, i in typeOptions" :key="i" :label="item.label" :value="item.label" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-button type="primary" @click="handleaddAssignedTask">新增交办事项</el-button>
            <span class="all-num-box">已完成<b class="green">{{ completedCount }}</b>个 进行中<b class="blue">{{
                    uncompletedCount }}</b>个</span>
        </div>
        <el-table :data="rolesList" style="width: 100%;margin-top:16px;" border class="table-box" v-loading="loading"
            :height="height + 'px'">
            <el-table-column align="center" label="序号" width="60">
                <template slot-scope="scope">
                    {{ (pagination.pageNum - 1) * pagination.pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="提出时间" width="120">
                <template slot-scope="scope">
                    {{ scope.row.proposeTime }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="提出领导" width="90">
                <template slot-scope="scope">
                    {{ scope.row.proposeLeader }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="工作要求" width="300">
                <template slot-scope="scope">
                    {{ scope.row.jobRequirement }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="完成时限" width="100">
                <template slot-scope="scope">
                    {{ scope.row.finishTime }}
                </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="工作计划">
                <template slot-scope="scope">
                    {{ scope.row.jobPlan }}
                </template>
            </el-table-column> -->
            <el-table-column align="center" label="责任科室" width="120">
                <template slot-scope="scope">
                    {{ scope.row.deptName }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="工作状态" width="80">
                <template slot-scope="scope">
                    <span :style="{ color: getColor(scope.row.finishState) }">{{ scope.row.finishState }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="工作进展">
                <template slot-scope="scope">
                    {{ scope.row.workProgress }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="140">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleEdit(scope)">编辑</el-button>
                    <el-button type="text" @click="handleDelete(scope)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize"
            @pagination="getPagination" />
        <!-- <el-dialog :visible.sync="dialogVisible" title="目标认领" :close-on-click-modal="false"
      width="70%">
      <addDialog />
      <div style="text-align:right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog> -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : '新增'" top="10vh"
            :close-on-click-modal="false">
            <el-form :model="role" label-width="80px" label-position="right" :rules="rules" ref="ruleForm">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="提出时间" prop="proposeTime">
                            <el-date-picker v-model="role.proposeTime" type="date" placeholder="选择日期"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="提出领导" prop="proposeLeader">
                            <el-input v-model="role.proposeLeader" placeholder="请输入提出领导" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="工作要求" prop="jobRequirement">
                            <el-input v-model="role.jobRequirement" placeholder="请输入工作要求" type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="责任科室" prop="deptName">
                            <el-select v-model="role.deptName" placeholder="请选择责任科室" clearable multiple>
                                <el-option v-for="item in ksList" :key="item.label" :label="item.label"
                                    :value="item.label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="工作状态" prop="finishState">
                            <el-select v-model="role.finishState" placeholder="请选择" clearable>
                                <el-option v-for="item, i in typeOptions" :key="i" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="完成时限" prop="finishTime">
                            <el-input v-model="role.finishTime" placeholder="请输入完成时限" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="24">
                        <el-form-item label="工作计划" prop="jobPlan">
                            <el-input v-model="role.jobPlan" placeholder="请输入工作计划" type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="24">
                        <el-form-item label="工作进展">
                            <el-input v-model="role.workProgress" placeholder="请输入工作进展" type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="text-align:right;">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRole">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import path from 'path'
import { getAssignedTaskList, addAssignedTask, deleteAssignedTask, updateAssignedTask } from '@/api/api'
import Pagination from '@/components/Pagination'
import addDialog from './components/addDialog.vue'
const defaultRole = {
    deptName: []
}

export default {
    name: 'work',
    components: { Pagination, addDialog },
    data() {
        return {
            typeOptions: [
                { label: '进行中' },
                { label: '已完成' }
            ],
            ksList: orgList,
            rowfinishState: 0,
            rules: {
                proposeTime: [
                    { required: true, message: '请选择提出时间', trigger: 'change' }
                ],
                proposeLeader: [
                    { required: true, message: '请输入提出领导', trigger: 'change' }
                ],
                jobRequirement: [
                    { required: true, message: '请输入工作要求', trigger: 'change' }
                ],
                // finishTime: [
                //     { required: true, message: '请输入完成时限', trigger: 'change' }
                // ],
                // jobPlan: [
                //     { required: true, message: '请输入工作计划', trigger: 'change' }
                // ],
                deptName: [
                    { required: true, message: '请选择责任科室', trigger: 'change', type: "array" }
                ],
                finishState: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                ],
            },
            loading: false,
            height: 400,
            changetypeOptions: [
                {
                    value: 0,
                    label: '待开始'
                },
                {
                    value: 1,
                    label: '进行中'
                },
            ],
            options: [],
            total: 0,
            completedCount: 0,
            uncompletedCount: 0,
            role: Object.assign({}, defaultRole),
            routes: [],
            rolesList: [],
            dialogVisible: false,
            dialogType: 'new',
            checkStrictly: false,
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            search: { executor: '' },
            pfOptions: [],
            zxOptions: [],
            pagination: {
                'pageNum': 1,
                'pageSize': 20
            },
            time: null,
        }
    },
    watch: {
        dialogVisible(val) {
            if (!val) {
                this.role = { deptName: [] }
                this.options = []
                this.$refs['ruleForm'].resetFields();
            }
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            if (to.path == '/work/list') {
                vm.onSubmit();
            }
        });
    },
    computed: {
        routesData() {
            return this.routes
        }
    },
    created() {
        this.getTasks();
        this.height = this.getHeight();
        let that = this;
        window.onresize = function (event) {
            that.height = that.getHeight();
        };
    },
    methods: {
        getHeight() {
            let winHieght = window.innerHeight;
            return winHieght - 280;
        },
        getStateName(state) {
            let find = this.typeOptions.find(item => item.value == state)
            return find?.label || state || ''
        },
        onSubmit() {
            this.pagination = {
                "pageNum": 1,
                "pageSize": 20
            }
            this.getTasks()
        },
        reset() {
            this.search = {}
            this.onSubmit()
        },
        getPagination(pagination) {
            this.pagination = pagination
            this.getTasks()
        },
        getColor(finishState) {
            const colors = {
                '超前': '#1ecd00',
                '正常': '#1ecd00',
                '已完成': '#1ecd00',
                '进行中': '#1890ff',
                '待开始': '#999',
                '已延期': '#ff4949',
                '落后': '#ff4949'
            }
            return colors[finishState]
        },
        truncateToFixed(value, decimals) {
            const integerPart = Math.trunc(value || 0); // 获取整数部分
            const decimalPart = value - integerPart; // 获取小数部分
            const factor = Math.pow(10, decimals);
            const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
            return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
        },
        goDetail(scope) {
            this.$router.push({
                path: `/work/detail/${scope.row.id}`
            })
        },
        async getTasks() {
            try {
                this.loading = true
                const res = await getAssignedTaskList({ page: this.pagination.pageNum, size: this.pagination.pageSize, ...this.search, distributor: localStorage.getItem('userName'), taskType: '20' });
                this.total = res.data.total || 0;
                this.completedCount = res.data.completedCount || 0;
                this.uncompletedCount = res.data.uncompletedCount || 0;
                this.rolesList = res?.data?.pageInfo?.list || [];
                this.loading = false
            } catch (error) {
                this.loading = false
            }
        },

        // Reshape the routes structure so that it looks the same as the sidebar
        generateRoutes(routes, basePath = '/') {
            const res = []

            for (let route of routes) {
                // skip some route
                if (route.hidden) { continue }

                const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

                if (route.children && onlyOneShowingChild && !route.alwaysShow) {
                    route = onlyOneShowingChild
                }

                const data = {
                    path: path.resolve(basePath, route.path),
                    title: route.meta && route.meta.title

                }

                // recursive child routes
                if (route.children) {
                    data.children = this.generateRoutes(route.children, data.path)
                }
                res.push(data)
            }
            return res
        },
        generateArr(routes) {
            let data = []
            routes.forEach(route => {
                data.push(route)
                if (route.children) {
                    const temp = this.generateArr(route.children)
                    if (temp.length > 0) {
                        data = [...data, ...temp]
                    }
                }
            })
            return data
        },
        handleaddAssignedTask() {
            this.role = Object.assign({}, defaultRole)
            if (this.$refs.tree) {
                this.$refs.tree.setCheckedNodes([])
            }
            this.dialogType = 'new'
            this.dialogVisible = true
        },
        async handleEdit(scope) {
            await this.getEdit(scope)
        },
        getEdit(scope) {
            let deptName = scope.row.deptName.split(',')
            this.rowfinishState = scope.row.finishState
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.checkStrictly = true
            this.role = { ...scope.row, deptName }
            this.$nextTick(() => {
                const routes = this.generateRoutes(this.role.routes)
                this.$refs.tree.setCheckedNodes(this.generateArr(routes))
                // set checked state of a node not affects its father and child nodes
                this.checkStrictly = false
            })
        },
        handleDelete({ $index, row }) {
            this.$confirm('确认删除当前交办事项?', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    deleteAssignedTask(row.id).then(res => {
                        if (res.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            })
                            this.getTasks();
                        } else {
                            this.$message({
                                type: 'warning',
                                message: res.message
                            })
                            this.getTasks();
                        }
                    })
                })
                .catch(err => { console.error(err) })
        },
        confirmRole() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    const isEdit = this.dialogType === 'edit'
                    if (isEdit) {
                        let deptName = this.role.deptName.join(',')
                        updateAssignedTask({ ...this.role, deptName }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                            this.options = []
                        })
                    } else {
                        let deptName = this.role.deptName.join(',')
                        addAssignedTask({ ...this.role, deptName }).then(res => {
                            this.dialogVisible = false
                            this.getTasks()
                            this.options = []
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // reference: src/view/layout/components/Sidebar/SidebarItem.vue
        onlyOneShowingChild(children = [], parent) {
            let onlyOneChild = null
            const showingChildren = children.filter(item => !item.hidden)

            // When there is only one child route, the child route is displayed by default
            if (showingChildren.length === 1) {
                onlyOneChild = showingChildren[0]
                onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
                return onlyOneChild
            }

            // Show parent if there are no child route to display
            if (showingChildren.length === 0) {
                onlyOneChild = { ...parent, path: '', noShowingChildren: true }
                return onlyOneChild
            }

            return false
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    overflow-y: auto;
    height: calc(100vh - 86px);
    padding: 16px 20px 0;

    .roles-table {
        margin-top: 30px;
    }

    .permission-tree {
        margin-bottom: 30px;
    }
}


.filter-container {
    ::v-deep .el-form-item {
        margin-bottom: 0;
    }
}

::v-deep .el-select,
::v-deep .el-date-editor.el-input,
::v-deep .el-date-editor.el-input__inner {
    width: 100%;
}

.table-box {
    ::v-deep .el-button--medium {
        padding: 0px 5px;
    }
}

.popover-list {
    min-height: 30px;
    line-height: 30px;
    cursor: pointer;
    padding: 0 10px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;

    &:hover {
        background: #f3f6fb;
    }
}

.all-num-box {
    margin-left: 20px;

    .green {
        color: #1ecd00;
        margin: 0 2px;
    }

    .blue {
        color: #1890ff;
        margin: 0 2px;
    }
}
</style>
<style>
.popper-list {
    padding: 0;
}

.popperClass {
    width: 500px;
}
</style>